<template>
  <div>
    <!-- 这个 div 将被 Coze SDK 使用 -->
    <div class="aiIcon"
          ref="dragBox"
          draggable="true"
          @mouseover="showTooltip"
          @mouseout="hideTooltip"
          @mousedown="startDrag">
      <img src="../../assets/images/home/xiaofu.gif" />
      <div class="tooltip" id="tooltip">Hi~我是您的专属个人助手小服同学！今天有什么可以帮您？</div>
      <div class="tooltip-arrow"></div>
    </div>

    <!-- 放置coze聊天框 -->
    <div id="cozeChatBox"></div>
  </div>
</template>
<script src="https://www.itxst.com/package/vue/vue.min.js"></script>
<script>
import { mapState } from "vuex";
import axios from 'axios';
import { ref } from 'vue';
let cozeWebChat = null
export default {
  name: "messageVoice",
  data() {
    return {
      isShowCoze:false,
      isDragging: false,
      offsetX: 0,
      offsetY: 0,
      sdkClient:null,
      // 用于判定拖动和点击
      threshold:5,
      hoverTimer:null,
      UserName:''
    };
  },
  components: {
    //callRoom,
  },
  computed: {
    ...mapState({
      currentUserId: (state) => state.currentUserId, //当前的用户id
      userInfoDetails: (state) => state.userInfoDetails,
      loginUserInfo: (state) => state.loginUserInfo,
    }),
  },
  created() {
    this.getaccesstoken()
    this.UserName = this.userInfoDetails.residents[0].userName
  },
  mounted(){
    // this.init()
  },
  destroyed() {
  },
  methods: {
    // 加载CozeSDK
    loadCozeSDK() {
      // 动态创建 script 标签加载 Coze SDK
      const script = document.createElement('script');
      script.src =
        'https://lf-cdn.coze.cn/obj/unpkg/flow-platform/chat-app-sdk/1.2.0-beta.15/libs/cn/index.js';
      script.onload = () => {        
        // SDK 加载完成后初始化
          if (window.CozeWebSDK) {
            this.initCozeChat();

          } else {
            console.error('SDK 加载失败或未定义 CozeWebSDK');
          }
      };
      document.head.appendChild(script);
    },
    // 初始化coze智能体
    initCozeChat() {
      // eslint-disable-next-line no-undef
      console.log('CozeWebSDK',CozeWebSDK);
      // eslint-disable-next-line no-undef
      if (CozeWebSDK) {        
      // eslint-disable-next-line no-undef
        cozeWebChat = new CozeWebSDK.WebChatClient({
          config: {
            botId: '7514524413467869203', // 替换为你的 Bot ID
          },
          auth: {
            type: 'token',
            token: this.cozeaccesstoken, // 替换为你的 Token
            onRefreshToken: () =>
              this.cozeaccesstoken, // 可选：刷新 Token
          },
          // 用户信息
          userInfo: {
              id: this.currentUserId,
              // url: 'https://lf-coze-web-cdn.coze.cn/obj/coze-web-cn/obric/coze/favicon.1970.png',
              nickname: this.UserName,
            },
          ui: {
            base: {
                icon: 'https://kh.tyzfchina.com.cn:8082/wx/xiaofubudong.png',
                layout: 'pc',
                zIndex: 1000,
                lang: 'zh-CN'
            },
            header: {
              isShow: true,
              isNeedClose: false
            },
            asstBtn: {
              isNeed: false,
            },
            footer: {
              isShow: false,
            },
            chatBot: {
              title: "小服同学",
              uploadable: true,
              width: 500,
              // width: 1000,
              el: document.getElementById('cozeChatBox'),
              isNeedAudio: true,
              onHide: () => {
                this.isShowCoze = false
                document.getElementById('cozeChatBox').style.pointerEvents = "none"
              },
              onShow: () => {
                this.isShowCoze = true
                document.getElementById('cozeChatBox').style.pointerEvents = "auto"
                this.hideTooltip()
              },
            },
          },
        })
        this.createUsername()
      } else {
        console.error('CozeWebSDK 未正确加载');
      }
    },
    // 获取access_token
    async getaccesstoken(){
      try {
        const response = await axios.get(`https://tyzfbj.com/avatar/ai/coze/permission/oauth2/token?sessionName=${this.currentUserId}`, {
          headers: {
            'Authorization': 'Bearer nikoyose.851896333#'
          }
        });
        console.log('response',response)
        if(response.data.code !== 0){
          // 获取token失败
          this.cozeaccesstoken = 'pat_zs0OqhdHWsPhICZB7p89mfTmJwP37GWVO5FW5bo7TEJ5kXlUyx6i9ghd9XUIGYME'
        }else{
          this.cozeaccesstoken = JSON.parse(response.data.data).access_token
        }
        this.loadCozeSDK()
        console.log('响应数据---------------------------:', this.cozeaccesstoken);
      } catch (err) {
        console.error('请求失败:', err.response ? err.response.data : err.message);
      }
    },
    //修改用户变量的值（用户变量字段在扣子空间中查看）
    async createUsername() {
      console.log('this.UserName',this.UserName);
      
      const apiUrl = "https://api.coze.cn/v1/variables";
      const params = {
        bot_id: "7514524413467869203",
        connector_id: "999",
        connector_uid: this.currentUserId,
        data: [
          {
            keyword: "username",
            value:this.UserName,
          },
        ],
      };
      const config = {
        headers: {
          Authorization: `Bearer ${this.cozeaccesstoken}`,
          "Content-Type": "application/json",
        },
      };
      axios
        .put(apiUrl, params, config)
        .then((response) => {
          console.log("响应数据----------------------:", response.data);
        })
        .catch((error) => {
          console.error("请求出错:", error.response?.data || error.message);
        });
    },
    // 显示提示框
    showTooltip(){
      let tooltip = document.getElementById('tooltip');
      this.hoverTimer = setTimeout(() => {
        if (!this.isShowCoze) {
            tooltip.style.visibility = 'visible';
            document.querySelector('.tooltip-arrow').style.visibility = 'visible';
        }
      }, 1000);
    },
    // 隐藏提示框
    hideTooltip(){
      let tooltip = document.getElementById('tooltip');
      if(this.hoverTimer){
        clearTimeout(this.hoverTimer);
        this.hoverTimer = null
      }
      tooltip.style.visibility = 'hidden';
      document.querySelector('.tooltip-arrow').style.visibility = 'hidden';
    },
    // 开始拖拽
    startDrag(e) {
      this.hideTooltip()
      // 阻止浏览器默认事件禁止拖拽
      e.preventDefault()
      let startX = e.clientX;
      let startY = e.clientY;
      const rect = this.$refs.dragBox.getBoundingClientRect();
      this.offsetX = e.clientX - rect.left;
      this.offsetY = e.clientY - rect.top;
      const rootFontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
      const windowWidth = window.innerWidth;
      const windowHeight = window.innerHeight;
      const dragBox = this.$refs.dragBox;
      const boxWidth = dragBox.offsetWidth;
      const boxHeight = dragBox.offsetHeight;
      const tooltip = document.querySelector('#tooltip')
      const tooltipArrow = document.querySelector('.tooltip-arrow')
      const cozeChatBox = document.querySelector('#cozeChatBox')

      let newLeft = e.clientX - this.offsetX;
      let newTop = e.clientY - this.offsetY;
      let newRight = windowWidth - newLeft - boxWidth;
      let newBottom = windowHeight - newTop - boxHeight;

      const onDrag =(e)=>{
        // 展示智能体弹窗时不能拖拽
        if(this.isShowCoze)return
        const diffX = Math.abs(e.clientX - startX);
        const diffY = Math.abs(e.clientY - startY);
        if (diffX > this.threshold || diffY > this.threshold) {
            this.isDragging = true;
        }
        newLeft = e.clientX - this.offsetX;
        newTop = e.clientY - this.offsetY;
        newRight = windowWidth - newLeft - boxWidth;
        newBottom = windowHeight - newTop - boxHeight;
        // 限制拖动范围在页面四周边界的20px内
        newLeft = Math.max(10, Math.min(newLeft, windowWidth - boxWidth - 10));
        newRight = Math.max(10, Math.min(newRight, windowWidth - boxWidth - 10));
        newTop = Math.max(10, Math.min(newTop, windowHeight - boxHeight - 10));
        newBottom = Math.max(10, Math.min(newBottom, windowHeight - boxHeight - 10));

        dragBox.style.position = 'fixed';
        dragBox.style.left = `${newLeft}px`;
        dragBox.style.top = `${newTop}px`;
      }
      const stopDrag = ()=>{
        if (!this.isDragging) {
          // 判断处于非拖拽状态时
          if (cozeWebChat) {
            // 打开或关闭智能体弹窗
            if(!this.isShowCoze){
              cozeWebChat.showChatBot()
            }else{
              cozeWebChat.hideChatBot()
            }
          }
        }else{
          this.isDragging = false;
        }

        // 提示框显示位置
        // 图标在左侧边界时，提示框偏右展示
        if(newLeft < ((tooltip.offsetWidth - boxWidth )/2 + 10)){
          tooltip.style.left = `${(-newLeft + 10)/rootFontSize}rem`;
        }else if(newRight < ((tooltip.offsetWidth - boxWidth )/2 + 10)){
          // 图标在右侧边界时，提示框偏左展示
          tooltip.style.left = `${-(tooltip.offsetWidth - boxWidth - newRight + 10)/rootFontSize}rem`
        }else{
          // 正常情况提示框居中显示
          tooltip.style.left = `${(boxWidth - tooltip.offsetWidth)/2/rootFontSize}rem`
        }
        // 图标在上侧边界时，提示框在图标下方展示
        if(newTop < (tooltip.offsetHeight + 10)){
          tooltipArrow.style.bottom = '-1%'
          tooltipArrow.style.borderColor = 'transparent transparent #f9f9f9 transparent'
          tooltip.style.bottom = `-${tooltip.offsetHeight/rootFontSize}rem`
        }else{
          // 其余情况提示框均在图标上方展示
          tooltipArrow.style.bottom = '92%'
          tooltipArrow.style.borderColor = '#f9f9f9 transparent transparent transparent'
          tooltip.style.bottom = '100%'
        }

        // 智能体弹窗显示位置
        // 左右
        // 图标在界面右侧，智能体显示在界面左侧
        if(rect.left > windowWidth/2){
          cozeChatBox.style.left = `${(rect.left - cozeChatBox.offsetWidth + 15)/rootFontSize}rem`
        }else{
          // 图标在左侧显示，智能体弹窗在界面右侧显示
          cozeChatBox.style.left = `${(rect.left + boxWidth - 15)/rootFontSize}rem`
        }
        // 上下
        // 图标在界面下侧显示，智能体弹窗在界面上侧显示。位置不够时贴顶展示
        if(rect.top > windowHeight/2){
          let top = rect.top - cozeChatBox.offsetHeight
          top = top > 0 ? top : 0
          cozeChatBox.style.top = `${(top + 15)/rootFontSize}rem`
        }else{
        // 图标在界面上侧显示，智能体弹窗在界面下侧显示，位置不够时贴底展示
          let top1 = rect.top + boxHeight
          top1 = windowHeight - top1 > cozeChatBox.offsetHeight ?  top1 : windowHeight - cozeChatBox.offsetHeight
          cozeChatBox.style.top = `${(top1 - 15)/rootFontSize}rem`
        }
        document.removeEventListener('mousemove', onDrag);
        document.removeEventListener('mouseup', stopDrag);
      }
      document.addEventListener('mousemove', onDrag);
      document.addEventListener('mouseup', stopDrag);
    }
  },
};
</script>
  <style scoped>
.aiIcon{
  width: 7rem;
  height: 7rem;
  position:fixed;
  right:0;
  bottom:5rem;
  cursor: pointer;
  z-index: 99;
}
.aiIcon img {
  width: 7rem;
  cursor: pointer;
}

#cozeChatBox{
  position: fixed;
  bottom: 4rem;
  width: 500px;
  height: 40rem;
  z-index: 100;
  right: 6rem;
  text-align: left;
  pointer-events: none;
}

.tooltip {
    position: absolute;
    left: 0;
    visibility: hidden;
    background-color: #f9f9f9;
    font-size: .875rem;
    color: #333;
    text-align: center;
    padding: .875rem;
    border-radius: .5rem;
    z-index: 1;
    bottom: 100%;
    left: -18rem; 
    white-space: nowrap;
    box-shadow: 0 5px 8px rgb(0 0 0 / 12%);
}

.tooltip-arrow {
    position: absolute;
    bottom: 92%;
    left: 50%;
    margin-left: -0.3125rem;
    border-width: 0.3125rem;
    border-style: solid;
    border-color: #f9f9f9 transparent transparent transparent;
    z-index:2;
}
</style>